<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link rel="stylesheet" href="./style.css">
  <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/highlight.js/11.6.0/styles/base16/onedark.min.css">
</head>
<body>
  <div id="RTF"></div>

  <script>
    let root = document.getElementById('RTF');
    let parentWindow = window.parent;

    window.addEventListener('message', event => {
      console.log("RTF stage: message event: ", event);
      let data = JSON.parse(event.data);
      if(data.type === 'sendArticle') {
        root.innerHTML = data.content;

        let links = document.getElementsByTagName('a');
        Array.from(links).forEach(link => {
          link.addEventListener('click', (event) => {
            event.preventDefault();
            parentWindow.open(link.href, "_blank");
          })
        })

        let imgs = root.querySelectorAll('IMG');

        let promises = [];

        imgs.forEach(img => {
          promises.push(new Promise(resolve => {
            img.onload = () => {
              resolve(img);
            }
          }))
        });

        Promise.all(promises).then(() => {
          parentWindow.postMessage({
            type: 'changeRTFHeight',
            content: root.scrollHeight
          });
        })
      }
    });

    console.log('stage load finish');
  </script>
</body>
</html>